package com.edu.dgut.service;

import com.edu.dgut.dao.dailysalesRepository;
import com.edu.dgut.dao.monthlysalesRepository;
import com.edu.dgut.entity.dailysalesEntity;
import com.edu.dgut.entity.monthlysalesEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

//更新销售额
@Service
public class salesService {

    @Autowired
    private dailysalesRepository dailysales;

    @Autowired
    private monthlysalesRepository monthlysales;

    //更新日月销售额
    public Map<String,Object> toDailyAndMonthly(BigDecimal sales_amount){
        int i = toDaily(sales_amount);
        int j = toMonthly(sales_amount);
        Map<String,Object> map = new HashMap<String,Object>();
        if(i==1&j==1) {
            map.put("status", 1);
        }else {
            map.put("status", 0);
        }
        return map;
    }

    //更新日销售额
    public int toDaily(BigDecimal sales_amount){
        dailysalesEntity daily = new dailysalesEntity();
        List<dailysalesEntity> old_daily = new ArrayList<>();
        int flag;
        //获取当前年月日,格式yyyy-MM-dd
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        daily.setDate(sdf.format(date));
        old_daily = dailysales.findByDate(sdf.format(date));
        if(old_daily.size() != 0) {
            int id = old_daily.get(0).getDailysales_id();
            daily.setDailysales_id(id);
            BigDecimal old_sales = old_daily.get(0).getSales_amount();
            sales_amount = sales_amount.add(old_sales);        //销售额
        }
        daily.setSales_amount(sales_amount);        //销售额
        daily = dailysales.save(daily);
        if(daily != null) {
            flag = 1;
        }else {
            flag = 0;
        }
        return flag;
    }

    //更新月销售额
    public int toMonthly(BigDecimal sales_amount){
        monthlysalesEntity monthly = new monthlysalesEntity();
        List<monthlysalesEntity> old_monthly = new ArrayList<>();
        int flag;
        //获取当前年月,格式yyyy-MM
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        monthly.setDate(sdf.format(date));
        old_monthly = monthlysales.findByDate(sdf.format(date));
        if(old_monthly.size() != 0) {
            int id = old_monthly.get(0).getMonthlysales_id();
            monthly.setMonthlysales_id(id);
            BigDecimal old_sales = old_monthly.get(0).getSales_amount();
            sales_amount = sales_amount.add(old_sales);        //销售额
        }
        monthly.setSales_amount(sales_amount);        //销售额
        monthly = monthlysales.save(monthly);
        if(monthly != null) {
            flag = 1;
        }else {
            flag = 0;
        }
        return flag;
    }
}
